package com.ccteam.admin.view.components

import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import androidx.core.content.res.use
import com.google.android.material.R
import com.google.android.material.button.MaterialButton
import com.google.android.material.progressindicator.CircularProgressIndicatorSpec
import com.google.android.material.progressindicator.IndeterminateDrawable

/**
 * @author Xiaoc
 * @since 2021/3/18
 */
class ProgressButton @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = R.style.Widget_MaterialComponents_Button): MaterialButton(context,attrs, defStyleAttr)  {

    private var isLoading = false

    private var progressColor: Int = Color.WHITE

    private val spec: CircularProgressIndicatorSpec = CircularProgressIndicatorSpec(context,null,0,
        com.ccteam.admin.R.style.Widget_MaterialComponents_CircularProgressIndicator_ExtraSmall)

    private var progressIndicatorDrawable: IndeterminateDrawable<CircularProgressIndicatorSpec>? = null
    init {
        val ta = context.obtainStyledAttributes(attrs,com.ccteam.admin.R.styleable.ProgressButton)
        ta.use {
            progressColor = ta.getColor(com.ccteam.admin.R.styleable.ProgressButton_progressColor,Color.WHITE)
        }
        spec.indicatorColors = intArrayOf(progressColor)
        progressIndicatorDrawable = IndeterminateDrawable.createCircularDrawable(context,spec)
        progressIndicatorDrawable?.setVisible(true,false)
        setLoading(false)
    }

    /**
     * 设置进度按钮点击事件
     * 会自动处理是否处于加载状态，如果不处于加载状态才响应点击事件
     */
    fun setProgressButtonOnClickListener(listener: OnClickListener){
        setOnClickListener {
            // 如果没有处于加载状态，才
            if(!isLoading){
                listener.onClick(it)
            }
        }
    }

    fun setLoading(newLoadingStatus: Boolean){
        if(isLoading == newLoadingStatus){
            return
        }
        if(newLoadingStatus){
            isLoading = newLoadingStatus
            icon = progressIndicatorDrawable
        } else {
            isLoading = false
            icon = null
        }
    }

    fun getLoadingStatus(): Boolean{
        return isLoading
    }
}